package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	ctx, cancelFunc := context.WithCancel(context.Background())

	go f1(ctx)
	go f2(ctx)

	time.Sleep(3 * time.Second)
	//关闭上下文通道，会导致两个子协程终止
	cancelFunc()

	time.Sleep(1 * time.Second)
}

func f1(ctx context.Context) {
	for {
		select {
		case <-ctx.Done():
			fmt.Println("f1终止")
			return
		default:
			fmt.Println("f1正在执行")
			time.Sleep(1 * time.Second)
		}
	}
}

func f2(ctx context.Context) {
	for {
		select {
		case <-ctx.Done():
			fmt.Println("f2终止")
			return
		default:
			fmt.Println("f2正在执行")
			time.Sleep(1 * time.Second)
		}
	}
}
